import axios from 'axios'
import {useUserStore} from '@/stores'
import {message} from 'ant-design-vue'
import translate from 'i18n-jsautotranslate'

// let loading = null
// const options = { content: '加载中...', lock: true, fullscreen: true, background: 'transparent', color: 'red' } // 加载中动画配置项
export default function (config) {
  const http = axios.create({
    baseURL: '/api',
    // baseURL: 'http://erp.yjinzi.com/index.php/',
    timeout: 50000,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Cache-Control': 'no-cache',
      'Content-Type': 'application/json'
    }
  })
  // 请求拦截器
  http.interceptors.request.use(
    config => {
      const {token} = useUserStore()
      // if(config.loading) loading = ElLoading.service(options)
      if (token) {
        // 添加token请求头
        config.headers['authorization'] = token
      }
      return config
    },
    err => {
      return Promise.reject(err)
    }
  )
  // 响应拦截器
  http.interceptors.response.use(
    res => {
      const {status, statusText, data} = res
      if (status === 200) {
        if (data.code === 1) {
          translate.execute();
          // 返回数据
          return data.data
        } else {
          const { loginToggle } = useUserStore()
          if(data.code === 401) {
            loginToggle(true)
          }
          message.error(data?.msg)
          return Promise.reject(data)
        }
      } else {
        message.error(statusText)
        return Promise.reject(statusText)
      }
    },
    err => {
      // 消除加载中动画
      // if(loading) loading.close()
      // ElMessage({ message: err.message, type: 'error' })
      return Promise.reject(err)
    }
  )
  return http(config)
}
